package com.pearadmin.pro.modules.training.controller;

import com.pearadmin.pro.common.aop.annotation.Log;
import com.pearadmin.pro.common.constant.ControllerConstant;
import com.pearadmin.pro.common.context.UserContext;
import com.pearadmin.pro.common.web.base.BaseController;
import com.pearadmin.pro.common.web.base.page.PageResponse;
import com.pearadmin.pro.common.web.domain.Result;
import com.pearadmin.pro.modules.laboratoryManagement.domain.ApplicationRequest;
import com.pearadmin.pro.modules.laboratoryManagement.domain.Applicationtable;
import com.pearadmin.pro.modules.laboratoryManagement.domain.Dangerousroom;
import com.pearadmin.pro.modules.sys.domain.SysUser;
import com.pearadmin.pro.modules.sys.service.SysUserService;
import com.pearadmin.pro.modules.training.entity.LaboratoryInfo;
import com.pearadmin.pro.modules.training.entity.TrainingApply;
import com.pearadmin.pro.modules.training.entity.TrainingConsumable;
import com.pearadmin.pro.modules.training.entity.TrainingEquipment;
import com.pearadmin.pro.modules.training.entity.vo.PageTrainingApplyVO;
import com.pearadmin.pro.modules.training.mapper.TrainingApplyMapper;
import com.pearadmin.pro.modules.training.service.TrainingApplyService;
import com.pearadmin.pro.modules.training.service.TrainingConsumableService;
import com.pearadmin.pro.modules.training.service.TrainingEquipmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 实训申请 Controller 接口
 *
 * @author ZhouXingYun
 * @version 1.0.0
 * @date 2022-06-27 10:37:36
 */
@Api(tags = {"实训申请"})
@RestController
@RequestMapping(ControllerConstant.PREFIX_SYS + "tac")
public class TrainingApplyController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(TrainingApplyController.class);

   private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    @Resource
    private TrainingApplyService trainingApplyService;
    @Resource
    private TrainingEquipmentService trainingEquipmentService;
    @Resource
    private TrainingConsumableService trainingConsumableService;

    @Resource // 用户基本信息
    private UserContext userContext;

    @Resource
    private SysUserService sysUserService;


    /**
     * 实训教室列表
     *
     * @param request 查询参数
     */
    @GetMapping("page")
    @Log(title = "实训教室列表")
    @ApiOperation(value = "实训教室列表")
    public Result page(PageTrainingApplyVO request) {
        PageResponse<TrainingApply> page = trainingApplyService.page(request);
        return success(page);
    }

    /**
     * 实训教室列表
     *
     * @param request 查询参数
     */
    @GetMapping("applyList")
    @Log(title = "实训教室列表")
    @ApiOperation(value = "实训教室列表")
    public Result applyList(PageTrainingApplyVO request) {
        List<TrainingApply> page = trainingApplyService.selectByEntity(request);
        page.forEach(trainingApply -> {
            if(trainingApply.getTaState().equals("0")){
                trainingApply.setTaState("待开始");
            }else if(trainingApply.getTaState().equals("1")){
                trainingApply.setTaState("使用中");
            }else if(trainingApply.getTaState().equals("2")){
                trainingApply.setTaState("已完结");
            }
            String createName = trainingApply.getCreateName();
            SysUser byId = sysUserService.getById(createName);
            trainingApply.setCreateName(byId.getNickname());
        });
        return success(page);
    }

    /**
     * 实训教室列表
     *
     * @param request 查询参数
     */
    @GetMapping("applyList_equiment")
    @Log(title = "实训教室列表")
    @ApiOperation(value = "实训教室列表")
    public Result applyList_equiment(PageTrainingApplyVO request) {
        request.setCreateName(userContext.getUserId());
        List<TrainingApply> page = trainingApplyService.selectByEntity(request);
        page.forEach(trainingApply -> {
            if(trainingApply.getTaState().equals("0")){
                trainingApply.setTaState("待开始");
            }else if(trainingApply.getTaState().equals("1")){
                trainingApply.setTaState("使用中");
            }else if(trainingApply.getTaState().equals("2")){
                trainingApply.setTaState("已完结");
            }
            String createName = trainingApply.getCreateName();
            SysUser byId = sysUserService.getById(createName);
            trainingApply.setCreateName(byId.getNickname());
        });
        return success(page);
    }

    @GetMapping("subscribe")
    @Log(title = "实验室预约")
    @ApiOperation(value = "实验室预约")
    public Result subscribe(LaboratoryInfo laboratoryInfo) {
        String returnState = "";
        int a = 0;
        // 开始时间
        String standby1 = laboratoryInfo.getStandby1();
        // 结束时间
        String standby2 = laboratoryInfo.getStandby2();
        //实验室ID
        Integer id = laboratoryInfo.getId();
        // 这几步是用来判断用户选择的时间段是否会和其他人预约的时间段冲突
        // 查询状态为0，1，（待开始，使用中）的该实验室的所有数据
        List<TrainingApply> applyList = new ArrayList<>();

        PageTrainingApplyVO trainingApply = new PageTrainingApplyVO();
        trainingApply.setTaName(String.valueOf(id));
        trainingApply.setTaType(0);
        for (int i = 0; i < 2; i++) {
            trainingApply.setTaState(String.valueOf(i));
            List<TrainingApply> aa = trainingApplyService.selectByEntity(trainingApply);
            if(aa!=null && aa.size()>0){
                for (TrainingApply trainingApply1 : aa) {
                    String startTime = trainingApply1.getStandby1();
                    String endTime = trainingApply1.getStandby2();
                    try {
                        String judge = judge1(format.parse(standby1), format.parse(standby2), format.parse(startTime), format.parse(endTime));
                        if(judge.equals("0")){
                            // 说明时间有冲突
                            String createName = trainingApply1.getCreateName();
                            SysUser byId = sysUserService.getById(createName);
                            return failure("您选择的时间与用户【"+byId.getNickname()+"】所预约的时间段有冲突，请重新选择！！！");
                        }
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                    applyList.add(trainingApply1);
                }
            }
        }
        // 没有冲突添加预约
        TrainingApply apply = new TrainingApply();
        apply.setCreateName(userContext.getUserId());
        apply.setTaName(String.valueOf(id));
        apply.setTaState(String.valueOf(0));
        apply.setTaNumber(1);
        apply.setTaType(0);
        apply.setRemark(laboratoryInfo.getRemark());
        apply.setCreateTime(LocalDateTime.now());
        apply.setStandby1(standby1);
        apply.setStandby2(standby2);
        apply.setStandby3(laboratoryInfo.getStandby3());
        boolean save = trainingApplyService.save(apply);
        return auto(save);
    }

    @GetMapping("subscribeEquiment")
    @Log(title = "实验室设备预约")
    @ApiOperation(value = "实验室设备预约")
    public Result subscribeEquiment(TrainingEquipment trainingEquipment) {
        Integer id1 = trainingEquipment.getId();
        //实验室设备ID
        String id = trainingEquipment.getStandby5();
        // 获取绑定预约实训室
        TrainingApply byId = trainingApplyService.getById(id);


        // 更改设备剩余库存
        Integer emNumber = trainingEquipment.getEmNumber();
        String standby1 = trainingEquipment.getStandby1();
        int i = emNumber - Integer.valueOf(standby1);
        TrainingEquipment equipment = new TrainingEquipment();
        equipment.setId(id1);
        equipment.setEmNumber(i);
        boolean update = trainingEquipmentService.updateById(equipment);


        TrainingApply apply = new TrainingApply();
        apply.setCreateName(userContext.getUserId());
        apply.setTaName(String.valueOf(id1));
        apply.setTaState(String.valueOf(0));
        apply.setTaNumber(Integer.valueOf(trainingEquipment.getStandby1()));
        apply.setTaType(1);
        apply.setRemark(trainingEquipment.getRemark());
        apply.setCreateTime(LocalDateTime.now());
        apply.setStandby1(byId.getStandby1());
        apply.setStandby2(byId.getStandby2());
        apply.setStandby3(trainingEquipment.getStandby3());
        apply.setStandby4(String.valueOf(trainingEquipment.getLiId()));
        boolean save = trainingApplyService.save(apply);
        return auto(save);
    }
    @GetMapping("subscribeConsumable")
    @Log(title = "实验室耗材预约")
    @ApiOperation(value = "实验室耗材预约")
    public Result subscribeConsumable(TrainingConsumable trainingConsumable) {
        Integer id1 = trainingConsumable.getId();
        //实验室设备ID
        String id = trainingConsumable.getStandby5();
        // 获取绑定预约实训室
        TrainingApply byId = trainingApplyService.getById(id);


        // 更改设备剩余库存
        Integer emNumber = trainingConsumable.getCsNumber();
        String standby1 = trainingConsumable.getStandby1();
        int i = emNumber - Integer.valueOf(standby1);
        TrainingConsumable equipment = new TrainingConsumable();
        equipment.setId(id1);
        equipment.setCsNumber(i);
        boolean update = trainingConsumableService.updateById(equipment);


        TrainingApply apply = new TrainingApply();
        apply.setCreateName(userContext.getUserId());
        apply.setTaName(String.valueOf(id1));
        apply.setTaState(String.valueOf(0));
        apply.setTaNumber(Integer.valueOf(trainingConsumable.getStandby1()));
        apply.setTaType(2);
        apply.setRemark(trainingConsumable.getRemark());
        apply.setCreateTime(LocalDateTime.now());
        apply.setStandby1(byId.getStandby1());
        apply.setStandby2(byId.getStandby2());
        apply.setStandby3(trainingConsumable.getStandby3());
        apply.setStandby4(String.valueOf(trainingConsumable.getLiId()));
        boolean save = trainingApplyService.save(apply);
        return auto(save);
    }



    /**
     * 判断时间端 leftStartDate - leftEndDate 是否和 rightStartDate-rightEndDate有冲突
     * @author ZhouXingYun
     * @date 2022/6/28 9:46
     * @param leftStartDate
     * @param leftEndDate
     * @param rightStartDate
     * @param rightEndDate
     * @return java.lang.String
     */
    public String judge1(Date leftStartDate, Date leftEndDate, Date rightStartDate, Date rightEndDate) {
        /* 开始时间 */
//        Date leftStartDate = feesPreferential.getPreferentialStartTime();
//        /* 结束时间 */
//        Date leftEndDate = feesPreferential.getPreferentialEndTime();
//
//        /*比较的时间段*/
//        Date rightStartDate = (Date) feesPreferentialList.get(i).get("preferentialStartTime");
//        Date rightEndDate = (Date) feesPreferentialList.get(i).get("preferentialEndTime");

        /*判断*/
        if (((leftStartDate.getTime() >= rightStartDate.getTime())
                && leftStartDate.getTime() < rightEndDate.getTime())
                || ((leftStartDate.getTime() > rightStartDate.getTime())
                && leftStartDate.getTime() <= rightEndDate.getTime())
                || ((rightStartDate.getTime() >= leftStartDate.getTime())
                && rightStartDate.getTime() < leftEndDate.getTime())
                || ((rightStartDate.getTime() > leftStartDate.getTime())
                && rightStartDate.getTime() <= leftEndDate.getTime())){
//            return "两段时间存在交集";
            return "0";
        }
//        return "两段时间不存在交集";
        return "1";
    }


}
